package com.ems.service.impl.supers.action;

import com.ems.dao.supers.action.ActionDao;
import com.ems.dao.supers.action.GroupActionDao;
import com.ems.pojo.permission.Action;
import com.ems.pojo.permission.GroupAction;
import com.ems.service.supers.action.GroupActionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: 伟伟
 * @Date: 2019/10/5
 * @Description: 描述
 * @Version: 1.0
 */
@Service("groupActionService")
public class GroupActionServiceImpl implements GroupActionService {

    @Autowired
    private GroupActionDao groupActionDao;

    @Autowired
    private ActionDao actionDao;

    /**
     * 为指定角色添加权限
     * @param groupAction
     * @return
     */
    @Override
    public int addGroupAction(GroupAction groupAction) {
        //根据子权限的id查询查询该权限的信息
        Action childrenAction = actionDao.findActionById(groupAction.getAction_id());
        if(childrenAction.getParent_id() != 0){ //说名该权限是子权限
            GroupAction groupAction1 = groupActionDao.findGroupActionByGrIdAndActionId(groupAction.getGr_id(),childrenAction.getParent_id());

            //如果没父权限
            if(groupAction1 == null){
                //添加父权限信息
                groupActionDao.addGroupAction(new GroupAction(groupAction.getGr_id(),childrenAction.getParent_id()));
            }
        }

        int result = groupActionDao.addGroupAction(groupAction);

        return result;
    }

    /**
     * 为指定的角色删除权限
     * @param groupAction
     */
    @Override
    public void deleteGroupAction(GroupAction groupAction) {
        //查询该角色下面删除权限的所有信息
        Action action = actionDao.findActionById(groupAction.getAction_id());

        //删除对应的权限
        groupActionDao.deleteGroupAction(groupAction);

        if(action.getParent_id() != 0){ //说明该权限是子权限
            //查询指定父权限下面所有的子权限
            List<Action> childrenActionList = actionDao.getAllChildrenActionByParentId(action.getParent_id());

            //在group_action表中查询指定角色和子权限的集合
            List<GroupAction> groupActionList =  groupActionDao.findAllChildPermission(groupAction.getGr_id(),childrenActionList);


            //判断group_action表中是否只剩下对应角色的父权限了
            if(groupActionList.size() == 0){
                //把最后剩余的父权限删除掉
                groupActionDao.deleteGroupAction(new GroupAction(groupAction.getGr_id(),action.getParent_id()));
            }

        }
    }
}
